package com.aggregate.pay.ebcpay.support;

import java.text.SimpleDateFormat;
import java.util.Date;

import com.aggregate.pay.ebcpay.bean.AbstractData;
import com.aggregate.pay.ebcpay.bean.AbstractResult;
import com.aggregate.pay.ebcpay.support.utils.JSON;

/**
 * 银盈通代付接口API操作类抽象类
 * @author Moyq5
 * @date 2019年3月14日
 * @param <D>
 * @param <R>
 */
public abstract class AbstractClient<D extends AbstractData, R extends AbstractResult> implements Client<D, R> {
		
	private Merch merch;
	
	public AbstractClient(Merch merch) {
		this.merch = merch;
	}
	
	@Override
	public R execute(D data) {
		
		data.setIdMerchant(merch.merchNo());
		data.setVersion("1.0");
		data.setTypeSign("RSA");
		data.setReqNo("" + System.currentTimeMillis() + Math.round(Math.random() * 8999 + 1000));
		data.setReqTime(new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()));
		
		R result = null;
		try {
			
			String sign = Tool.sign(signString(data), merch.privateKey());
			data.setSign(sign);
			
			HttpClient client = Factory.getHttpClient();
			
			String reqJson = JSON.toString(data);
			String resJson = client.post(serverPath(), reqJson);
			result = JSON.toObject(resJson, resultClass());
			/*
			if (Tool.verify(result, Factory.getConfig().publicKey())) {
				
			}
			*/
			return result;
			
		} catch (Exception e) {
			log.error("接口调用失败", e);
			try {
				result = resultClass().newInstance();
			} catch (Exception e1) {
				e1.printStackTrace();
			}
			result.setRetCode("C9999");
			result.setRetMsg("本地错误：" + e.getMessage());
			result.setReqNo(data.getReqNo());
			result.setTypeChannel(data.getTypeChannel());
			result.setIdMerchant(data.getIdMerchant());
		}
		return result;
	}
	
	protected String serverPath() {
		return Factory.getConfig().serverPath();
	}

	protected abstract Class<R> resultClass();
	protected abstract String signString(D data);
}
